package com.cqc.googleplay.fragment.home;

import java.util.ArrayList;
import java.util.List;

import com.cqc.googleplay.R;
import com.cqc.googleplay.adapter.ClassifyFragAdapter;
import com.cqc.googleplay.bean.ClassicfyInfoBean;
import com.cqc.googleplay.bean.ClassifyFragBean;
import com.cqc.googleplay.http.HttpHelper;
import com.cqc.googleplay.http.NetUrl;
import com.cqc.googleplay.utils.CommonUtil;
import com.cqc.googleplay.utils.GsonUtil;
import com.cqc.googleplay.utils.LogUtil;
import com.cqc.googleplay.utils.ToastUtil;
import com.cqc.googleplay.view.ContentPager;
import com.google.gson.reflect.TypeToken;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

/**
 * 分类
 * 
 * @author Administrator
 */
@SuppressWarnings({ "unchecked"})
public class ClassifyFrag extends Fragment {

	private static final String TAG = "ClassifyFrag";
	private View rootView;
	private ListView listView;
	private ContentPager contentPager;
	private ArrayList<Object> list = new ArrayList<Object>();
	private ClassifyFragAdapter adapter;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		contentPager = new ContentPager(getActivity()) {

			@Override
			public Object requestData() {
				return getData();
			}

			@Override
			public View createSuccessView() {
				return getSuccessView();
			}
		};
		return contentPager;
	}

	protected View getSuccessView() {
		rootView = View.inflate(getActivity(), R.layout.frag_classify, null);
		listView = (ListView) rootView.findViewById(R.id.listView_frag_classify);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				int itemViewType = adapter.getItemViewType(position);
				if (itemViewType == ClassifyFragAdapter.ViewTypeInfo) {
					view.setClickable(true);
					ToastUtil.showShortToast("" + position + adapter.getItemId(position));
				} else {
					view.setClickable(false);
				}
			}
		});
		return rootView;
	}

	protected Object getData() {
		String json = HttpHelper.get(NetUrl.CLASSIFY);
		List<ClassifyFragBean> classifyList = (List<ClassifyFragBean>) GsonUtil.jsonToList(json, new TypeToken<List<ClassifyFragBean>>() {
		}.getType());

		for (ClassifyFragBean classify : classifyList) {
			list.add(classify.getTitle());
			List<ClassicfyInfoBean> inofs = classify.getInfos();
			list.addAll(inofs);
		}

		if (list.size() > 0) {
			LogUtil.d(TAG, "list=" + list);
			CommonUtil.runOnUIThread(new Runnable() {
				@Override
				public void run() {
					adapter = new ClassifyFragAdapter(list);
					listView.setAdapter(adapter);
				}
			});
		}
		return classifyList;
	}
}
